$(document).ready(function() {
   var resumecontent = $("#resumecontent"); 

   var loadResume=function(source) {
      $.get(OC.filePath('resumes', 'ajax', 'getresume.php') + '?id='+ resumecontent.data('id')+"&source="+source+"&_t="+resumecontent.data('added'), function(html) {
         var iframes = html.split('<div id="_ppp_iframe_delimiter"></div>'); 
         resumecontent.html('');
         $.each(iframes, function(i, html) {
            resumecontent.append("<iframe id='resumecontent"+i+"' frameborder='0' style='border:none; width:100%; overflow: hidden'></iframe>");
            var iframe = $('#resumecontent'+i, resumecontent); 
            var doc = iframe.get(0).contentWindow.document; 
            doc.open();
            doc.write(html);
            doc.close();
            iframe.height($(doc).height()+(i==0 ? 50 : 100));
            iframe.one('load',function(){
               iframe.height($(doc).height()+(i==0 ? 50 : 100));
            });
            // reset the iframe height based on image loading completion 
            $(doc).find('img').filter(function(i) { return $(this).attr('src') && /data:image/.test($(this).attr('src'));}).each(function() {
               $(this).one('load', function() {
                  iframe.height($(doc).height()+10);
               }).each(function() {
                  /* if load from browser cache, we have complete property */
                  if(this.complete) $(this).load();
               });
            });
            resizeAppHeight();
         })
      })
   };
   loadResume(resumecontent.data('source').split(',').shift());
   
   $('.resumedetail_tabbox li').on('click', 'a', function(event) {
      if($(this).hasClass('active')) return false;
      resumecontent.html("<img src='/images/3/loadm.gif'></img>");
      loadResume($(this).hasClass('51job') ? '51job' : ($(this).hasClass('zhilian') ? 'zhilian':($(this).hasClass('jiancai') ? 'jiancai' : 'upload')));
      $(this).parents('ul').find("li").removeClass('active');
      $(this).parent().addClass('active');
      return false;
   })
   
   $('#resume_action_panel').on('click', '.download', function(event) {
      var resume = resumecontent.attr('data-id');
      OC.Notification.show(t('resumes','Your download is being prepared. This might take some time if the resume is big.'), 5000);
      if ( (downloadURL = document.getElementById("downloadURL")) ) {
         window.location=downloadURL.value+"&download&ids="+resume;
      } else {
         window.location=OC.filePath('resumes', 'ajax', 'download.php') + '?ids='+ resume;
      }
      
      // when download finish, hide notification
      var downloadObj = window.setInterval(function(){
         if ($.cookie('DOWNLOAD_DONE')) {
            OC.Notification.hide();
            $.cookie('DOWNLOAD_DONE', null);
            window.clearInterval(downloadObj);
            return;
         }
      }, 1000);
      
      return false;
   });

   $('#resume_action_panel').on('click', '.delete', function(event) {
      var target = $(this); 
      var resume = resumecontent.attr('data-id');
      event.preventDefault();
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'delete.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               resumecontent.find("iframe").fadeTo('fast', 0.3);
               var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text(); 
               OC.Notification.showHtml(resumecontent.attr('data-name') + ' － 应聘职位<strong>'+ jobtitle + '</strong>的简历被删除进回收站。'+'<span class="undo restoreone">'+t('resumes', 'undo')+'</span>', 3000, function(){
                  var next = $("#resume_action_panel").find("a.next, a.prev").get().pop();
                  if(next){
                     window.location = $(next).attr("href");
                  }
                  else{
                     var folder =  $(".hr_inner_navigate li.cur_li a");  
                     window.location = folder.data("href") ? folder.data("href") : folder.attr("href");
                  }
               });
            }
            else {
               showMessagePanel(result.error, target, true, {placement:"bottom"});
            }
         }   
      });
      return false;
   });

   $('#resume_action_panel').on('click', '.save', function(event) {
      var target = $(this); 
      event.preventDefault();
      target.tooltip("hide");
      var resume = resumecontent.attr('data-id');
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'save.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text();
               OC.Notification.showHtml(resumecontent.attr('data-name') + ' － 应聘职位<strong>'+ jobtitle + '</strong>的简历被收藏。', 3000);
               var html = '<a href="" class="unsave" title="点击取消收藏简历" data-placement="right">';
               html += '<img class="svg" src="/themes/jobs/core/img/actions/close.png" alt="取消收藏">';
               html += '已收藏</a>';
               $("#savestatus .save").tooltip("hide");
               $("#savestatus").html(html);
               $("#savestatus .unsave").tooltip();
            }
            else {
               showMessagePanel(result.error, target, true, {placement:"bottom"});
            }
         }
      });

      return false;
   });


   $('#resume_action_panel').on('click', '.unsave', function(event) {
      var target = $(this);
      event.preventDefault();
      target.tooltip("hide");
      var resume = resumecontent.attr('data-id');
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'unsave.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text();
               OC.Notification.showHtml(resumecontent.attr('data-name') + ' － 应聘职位<strong>'+ jobtitle + '</strong>的简历已被取消收藏。', 3000);
               var html = '<a href="" class="save" title="点击收藏简历" data-placement="right">';
               html += '<img class="svg" src="/themes/jobs/core/img/actions/add.png" alt="收藏">';
               html += '未收藏</a>';
               $("#savestatus .unsave").tooltip("hide");
               $("#savestatus").html(html);
               $("#savestatus .save").tooltip();
            }
            else {
               showMessagePanel(result.error, target, true, {placement:"bottom"});
            }
         }
      });
      return false;
   });

   var restoreResume = function(target, callback) {
      var resume = resumecontent.attr('data-id');
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'restore.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               if($.isFunction(callback)) callback();
            }
            else {
               showMessagePanel(result.error, target, true, {placement:"bottom"});
            }
         }
      });
   }; 


   $('#resume_action_panel').on('click', '.restore', function(event) {
      event.preventDefault();
      restoreResume($(this), function() {
         var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text();
         OC.Notification.showHtml(resumecontent.attr('data-name') + ' － 应聘职位<strong>'+ jobtitle + '</strong>的简历已被恢复。', 3000, function() {
            var next = $("#resume_action_panel").find("a.next, a.prev").get().pop();
            if(next){
               window.location = $(next).attr("href");
            }
            else{
               var folder =  $(".hr_inner_navigate li.cur_li a");
               window.location = folder.data("href") ? folder.data("href") : folder.attr("href");
            }
         })
      }); 
      return false;
   });

   $('#resume_action_panel').on('click', '.permdelete', function(event) {
      event.preventDefault();
      var target = $(this);
      var resume = resumecontent.attr('data-id');
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'permdelete.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text();
               OC.Notification.showHtml(resumecontent.attr('data-name') + ' － 应聘职位<strong>'+ jobtitle + '</strong>的简历已被永久删除。', 3000, function() {
                  var next = $("#resume_action_panel").find("a.next, a.prev").get().pop();
                  if(next){
                     window.location = $(next).attr("href");
                  }
                  else{
                     var folder =  $(".hr_inner_navigate li.cur_li a");
                     window.location = folder.data("href") ? folder.data("href") : folder.attr("href");
                  }
               })
            }
            else {
               showMessagePanel(result.error, target, true, {placement:"bottom"});
            }
         }
      });

      return false; 
   });

   $('#resume_action_panel').on('click', '.share', function(event) {
      var target = $(this);
      event.preventDefault();
      var resume = resumecontent.data('id');
      var itemType = 'resumes';
      var possiblePermissions = resumecontent.data('permissions');
      var appendTo = $('#resume_action_panel'); 
      if (OC.Share.droppedDown) {
         OC.Share.hideDropDown();
      } else {
         OC.Share.showDropDown(itemType, resume, appendTo, true, possiblePermissions);
         $("#shareresumedialog").css({right:"auto",top:"auto",marginRight:"0"}).position({
            my: "left top+10",
            at: "left+3 bottom",
            of: target,
            collision:"none"
         });
      }
      return false; 
   });
   
   $('#resume_action_panel').on('click', '.infolder', function(event) {
      event.preventDefault();
      var resume = resumecontent.data('id');

      var scrolltops = $(window).scrollTop();
      $('#infolder_modal').css("top",scrolltops+75+"px").modal();
      
      $.ajax({
         type: "GET",
         url: OC.filePath('resumes', 'ajax', 'getinfolderlist.php'),
         data: {ids:JSON.stringify([resume])},
         beforeSend: function(xhr, settings) {
            showLoading($("#infolder_body"));
         },
         success: function(result){
            $("#infolder_body").html(result);
         }
      });
      
      return false; 
   });

   $('#notification').on('click', '.undo', function(){
      OC.Notification.clear();
      if($(this).hasClass("restoreone")) {
         restoreResume($(this), function() {
            resumecontent.find("iframe").css('opacity', 1);
         }); 
      }

      OC.Notification.hide();
      return false; 
   });
   
   function getAllowTagsNum() {
      var curTagsNum = $('#resumetags span').length;
      var allowTagsNum = 5 - curTagsNum;
      if(allowTagsNum < 0) {
         allowTagsNum = 0;
      }
      return allowTagsNum;
   }
   
   function updateAllowTagsNum() {
      var allowTagsNum = getAllowTagsNum();
      var tagitTagsNum = $('#resumetagsbox').tagit('assignedTags').length;
      
      allowTagsNum = allowTagsNum - tagitTagsNum;
      
      $('#allowtagsnum').attr('data-allownum', allowTagsNum);
      if(allowTagsNum < 0) {
         allowTagsNum = 0;
      }
      $('#allowtagsnum').text(allowTagsNum);
   }
   
   function fixTagsDialogPosition() {
      target = $('#addresumetags');
      var x = target.position().left;
      var y = target.position().top;
      $('#addresumetags_dialog').css({left:x-91+"px",top:y+30+"px"});
   }
   
   var rebuildTagsHtml = function(tags, admin) {
      var html = '', removeButton = '';
      $.each(tags, function(key, tag) {
         if(admin) {
            removeButton = "<i data-tagid='" + tag.id + "' class='icon-remove remove_tag'></i>";
         }
         html += "<span><a target='_blank' href=" + tag.href + ">" + tag.name + "</a>" + removeButton + "</span>";
      });
      
      return html;
   }
   
   $('#resumetags').on('click', '.remove_tag', function(){
      var target = $(this);
      var tagid = $(this).attr('data-tagid');
      var jobid = resumecontent.attr('data-jobid');
      var resumeid = resumecontent.attr('data-id');
      
      $.ajax({
         type: 'POST',
         url: OC.filePath('resumes', 'ajax', 'removeresumetag.php'),
         data: {jobid: jobid, tagid: tagid, resumeid: resumeid},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status === 'success') {
               $.ajax({
                  type: 'GET',
                  url: OC.filePath('resumes', 'ajax', 'rebuildtags.php'),
                  data: {jobid: jobid, resumeid: resumeid},
                  cache: false, 
                  success: function(result){
                     if (!isLoggedIn(result, target)) {
                        window.location = redirect_url;
                        return;
                     }
                     
                     if(!$.isPlainObject(result)) {
                        result = $.parseJSON(result);
                     }
                     
                     if(result.status === 'success') {
                        var tags = result.data.tags, admin = result.data.admin;
                        var html = rebuildTagsHtml(tags, admin);
                        $('#resumetags').html(html);
                        var allowTagsNum = getAllowTagsNum();
                        $('#resumetagsbox').tagit('option', 'maxNumTags', allowTagsNum);
                        updateAllowTagsNum();
                        fixTagsDialogPosition();
                     } else if(result.error) {
                        showMessagePanel(result.error, $('#resumetags'), true, {placement:'left'});
                     }
                  }
               });
            } else if(result.error) {
               showMessagePanel(result.error, target, true, {placement:'bottom'});
            }
         }
      });
   });
   
   $('#addresumetags').click(function(){
      var target = $(this);
      var allowTagsNum = getAllowTagsNum();
      $("#match_details_pop .closediv").trigger("click");
      
      if(allowTagsNum > 0) {
         $('#resumetagsbox').tagit('removeAll');
         $('#resumetagsbox').tagit('option', 'maxNumTags', allowTagsNum);
         updateAllowTagsNum();
         $('#addresumetags_form .server').html('').hide();
      	
         $.ajax({
            type: 'GET',
            url: OC.filePath('resumes', 'ajax', 'getresumehottags.php'),
            data: {resumeid: resumecontent.attr('data-id')},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               if(result.status === 'success') {
                  var html = '', hotTags = result.data;
                  $.each(hotTags, function(key, hotTag) {
                     html += '<li>' + hotTag.name + '</li>';
                  });
                  
                  $('#resumehottags').html(html);
                  fixTagsDialogPosition();
                  $('#addresumetags_dialog').fadeIn();
                  $('#resumetagsbox li.tagit-new input').val('').focus();
               } else if(result.error) {
                  showMessagePanel(result.error, target, true, {placement:'bottom'});
               }
            }
         });
      } else {
         showMessagePanel('最多只能添加5个标签，请先删除再添加', target, true, {placement:'bottom'});
      }
      
   });
   
   $('#addresumetags_form').on('click', '.addtarget_action', function(){
      $('#resumetagsbox li.tagit-new input').focus();
   });
   
   function checkDuplicateTag(tagname) {
      var isDuplicate = false;
      $('#resumetags span a').each(function(){
         if(tagname.toLowerCase() == $(this).text().toLowerCase()) {
            isDuplicate = true;
            return false;
         }
      });
      return isDuplicate ? false : true;
   }
   
   $('#addresumetags_form').on('click', '#resumehottags li', function(){
      var tagname = $(this).text();
      var allowtagsnum = $('#allowtagsnum').attr('data-allownum');
      
      if($(this).hasClass('selected')) {
         if(!$('#resumetagsbox').tagit('removeTagByName', tagname)) {
            return false;
         }
         $(this).removeClass('selected');
         
         allowtagsnum++;
         $('#allowtagsnum').attr('data-allownum', allowtagsnum);
         if(allowtagsnum < 0) {
            allowtagsnum = 0;
         }
         $('#allowtagsnum').text(allowtagsnum);
      } else {
         if(!checkDuplicateTag(tagname)) {
            $('#resumetagsbox li.tagit-new input').focus();
            $("#addresumetags_form .server").html("标签名已存在").addClass("error").removeClass("success").show().delay(1000).hide(400);
            return false;
         }
         
         if(!$('#resumetagsbox').tagit('createTag', tagname)) {
            return false;
         }
         $(this).addClass('selected');
         
         allowtagsnum--;
         $('#allowtagsnum').attr('data-allownum', allowtagsnum);
         if(allowtagsnum < 0) {
            allowtagsnum = 0;
         }
         $('#allowtagsnum').text(allowtagsnum);
      }
   });
   
   $('#closetagsdialog, #canceladdtags').click(function(){
   	$('#addresumetags_dialog').fadeOut();
   });
   
   $('#resumetagsbox').tagit({
      maxNumTags: 0,
      maxTagLength: 30,
      itemName: "tagit", 
      tagSource: function(req, add) {
         /* not used for now
         $.ajax({
            url: OC.filePath('resumes', 'ajax', 'getsearchtags.php'),
            data: {q: req.term},
            dataType: "json",
            global: false,
            success: function(data) {
              add(jQuery.map(data.tags, function(item) {
               return {
                  label: item,
                  value: item
               }
              }));
            }
         });
         */
      },
      caseSensitive: false,
      onTagBeforeAdd: function(maxTagLength, tag) {
         $('#addresumetags_form').data('tagerror', 0).find('.server').html('').hide();
         var maxlength = maxTagLength / 2;
         if(compact_strlen(tag) > maxlength) {
            $("#addresumetags_form .server").html("请输入1到30个字符长度的标签").addClass("error").removeClass("success").show();
            return false;
         }
         
         if(!checkDuplicateTag(tag)) {
            $('#resumetagsbox li.tagit-new input').focus();
            $('#addresumetags_form').data('tagerror', 1).find('.server').html('标签名已存在').addClass('error').removeClass('success').show();
            return false;
         }
         
         return true;
      },
      onError: function(error) {
         if(error.length <= 0) {
            $('#addresumetags_form').data('tagerror', 0).find('.server').html('').hide();
            return;
         }
         switch(error) {
            case 'ILLEGAL_TAG':
               error = '标签名含有非法字符';
               break;
            case 'DUPLICATE_TAG':
               error = '标签名重复';
               break;
            case 'NOMORE_TAG':
               error = '标签数已达上限';
               break;
            case 'TOOLONG_TAG':
               error = '请输入1到30个字符长度的标签';
               break;
            default:
               error = '标签不合法，请修改';
               break;
         }
         $('#addresumetags_form').data('tagerror', 1).find('.server').html(error).addClass('error').removeClass('success').show();
         // when TOOLONG error, don't set focus otherwise it will trigger maxlenght plugin onEdit callback again
         if(error != "TOOLONG_TAG")
            $('#resumetagsbox li.tagit-new input').focus();
      },
      onTagAdded: function(e, tag) {
         $('#resumetagsbox li.tagit-new input').focus();
         var tagname = tag.find('.tagit-label').text();
      	var allowtagsnum = $('#allowtagsnum').attr('data-allownum');
      	$('#resumehottags li').each(function(){
      	   if($(this).text() == tagname) {
      	      if(!$(this).hasClass('selected')) {
      	         $(this).addClass('selected');
      	      }
      	   }
      	});
      	
      	allowtagsnum--;
         $('#allowtagsnum').attr('data-allownum', allowtagsnum);
         if(allowtagsnum < 0) {
            allowtagsnum = 0;
         }
         $('#allowtagsnum').text(allowtagsnum);
      },
      onTagRemoved: function(e, tag) {
         $('#resumetagsbox li.tagit-new input').blur().focus();
         var tagname = tag.find('.tagit-label').text();
         var allowtagsnum = $('#allowtagsnum').attr('data-allownum');
         $('#resumehottags li').each(function(){
            if($(this).text() == tagname) {
               if($(this).hasClass('selected')) {
                  $(this).removeClass('selected');
               }
            }
         });
         
         if(tag.hasClass('tagit-choice')) {
            allowtagsnum++;
            $('#allowtagsnum').attr('data-allownum', allowtagsnum);
            if(allowtagsnum < 0) {
               allowtagsnum = 0;
            }
            $('#allowtagsnum').text(allowtagsnum);
         }
      }
   });
   
   $('#submitaddtags').mouseover(function() {
      $('#resumetagsbox li.tagit-new input').blur();
   });
   
   $('#addresumetags_form').ajaxForm({
      data: {jobid: resumecontent.attr('data-jobid'), resumeid: resumecontent.attr('data-id')},
      beforeSubmit: function(data, form, options) {
         tagerror = form.data('tagerror');
         if(tagerror) {
            $('#resumetagsbox li.tagit-new input').focus();
            return false;
         } else {
            var tags = $('#resumetagsbox').tagit('assignedTags');
            if(tags.length <= 0){
               $('#resumetagsbox li.tagit-new input').focus();
               $(".server", form).html("请至少输入一个标签!").addClass("error").removeClass("success").show().delay(3000).hide(400);
               return false;
            }
         }
         if(!showLoading(form))
            return false;
         $(".server", form).hide(); 
      },
      success: function(result, status, xhr, form) {
         if (!isLoggedIn(result)) {
            $(".server", form).jobUtil("showError", "您需要登陆");
            window.location = redirect_url;
            return;
         }
         
         if(!$.isPlainObject(result)) {
            result = $.parseJSON(result);
         }
         
         if (result.status === 'success') {
            $(".server", form).html('');
            
            $.ajax({
               type: 'GET',
               url: OC.filePath('resumes', 'ajax', 'rebuildtags.php'),
               data: {jobid: resumecontent.attr('data-jobid'), resumeid: resumecontent.attr('data-id')},
               cache: false, 
               success: function(result){
                  if (!isLoggedIn(result, target)) {
                     window.location = redirect_url;
                     return;
                  }
                  
                  if(!$.isPlainObject(result)) {
                     result = $.parseJSON(result);
                  }
                  
                  if(result.status === 'success') {
                     var tags = result.data.tags, admin = result.data.admin;
                     var html = rebuildTagsHtml(tags, admin);
                     $('#resumetags').html(html);
                  } else if(result.error) {
                     showMessagePanel(result.error, $('#resumetags'), true, {placement:'left'});
                  }
               }
            });
            
            $('#canceladdtags').trigger('click');
         } else if(result.error) {
            $(".server", form).html(result.error).addClass("error").removeClass("success").show();
         }
      }
   });

   $('.show_match_details.matched').on('click', function(e){

      var target = $(this); 
      var parentdiv = $("#match_details_pop");
      
      $.metadata.setType("attr", "data");
      var data = target.metadata();
      var resumeid = data.resumeid;
      
      if (parentdiv.length > 0) {
         if(parentdiv.css("display") != 'none') {
            parentdiv.hide();
         }
         else {
            parentdiv.show();
         }
      } 
      else {      
         $.ajax({
            type: "GET",
            url: OC.filePath('resumes', 'ajax', 'getmatchdetail.php'),
            data: {resumeid: resumeid},
            dataType: 'html',
            cache: false, 
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               $('body').append("<div id='match_details_pop' class='popup' style='position:absolute;display:none;z-index:3;'></div>");
               $("#match_details_pop").position({
                 my: "left top+6",
                 at: "left+20 bottom",
                 of: target
               }).html(result).show();
               $("#match_details_pop .hr_top5uppoint").css({left:118+"px",right:"auto"});
            }
         });
      }
      return false;
   });
   
   $('#resumestatus').click(function(){
      $(this).find('.resumestatus_option').toggle();
   });
      
   $('.resume_status_option_child').click(function(){
      var target = $(this);
      var jobid = resumecontent.attr('data-jobid');
      var resumeid = resumecontent.attr('data-id');
      var status_id = target.attr('data-status-id');
      var status_text = target.text();
      /* not used for now
      if(status_text == '--(未筛选)') {
         status_text = '--';
      }
      */
      
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'updatestatus.php'),
         data: {jobid: jobid, resumeid: resumeid, status_id: status_id},
         dataType: 'json',
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if(result.status === 'success') {
               $('#resumestatus em.resume_status_text').html(status_text);
            } else if(result.error) {
               showMessagePanel(result.error, $('#resumestatus'), true, {placement:'top'});
            }
         }
      });
   });
   
   // show persontest result
   $('body').on('click', '.check_persontest_result', function() {
      var target = $(this);
      if(!$(this).hasClass('gray')) {
         var uname = resumecontent.attr('data-name');
         var jobseeker_id = resumecontent.attr('data-id');
         $.ajax({
            type: "GET",
            url: OC.filePath('resumes', 'ajax', 'getpersontestresult.php'),
            data: {uname: uname, jobseeker_id: jobseeker_id},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               if(/id="modal_noresult"/.test(result)){
                  $('#persontest_noresult').html(result).modal();
                  $('.person_putsumer_f a').tooltip();
               }else{
                  $('#persontest_result').html(result).modal();
                  $('.person_putsumer_f a').tooltip();
               }
            }
         });
      }
   });
   
   // the below is to control modal show event and hidden event
   $('#persontest_result').on('show', function () {
      $(this).css('visibility', 'visible');
   });
   
   $('#persontest_result').on('hidden', function () {
      $(this).css('visibility', 'hidden').show();
   });

   // invite interview
   $(document).on('click', '.invite_interview #invite_abtn', function(){
      var target = $(this);
      $.metadata.setType("attr", "data");
      var data =$("#addevent").metadata();
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'onlineinter.php'),
         data: data,
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            $("#onlineinter_testdialog").html(result).modal();
            $('label.checkbox.gray').tooltip();
            setTimeout(function () {
               if(!$('#onlineinter_testdialog #sendemail').is(':checked')) {
                  if(!$('#onlineinter_testdialog #sendsms').is(':checked') && $('#onlineinter_testdialog #sendsms').attr("disabled") != "disabled") {
                     showMessagePanel('简历缺少Email信息，请设置发送短信', $("#onlineinter_testdialog #sendsms").parent("label"), true, {placement:'right'});
                  }
               }
            }, 500);
         }
      });
   });
   
   //如果短信和email都没有被勾选,按钮则为不能点击状态
   $(document).on('click', '#onlineinter_testdialog #sendsms', function(){
      if($('#onlineinter_testdialog #sendemail').is(':checked')) {
         if($(this).is(':checked'))
            $(this).val('sms');
         else
            $(this).val('');
         $("#onlineinter_button").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
      } else {
         if($(this).is(':checked')){
            $(this).val('sms');
            $("#onlineinter_button").removeClass("ppp_graybtn").addClass("ppp_bluebtn").css("cursor","pointer");
         }else{
            $(this).val('');
            $("#onlineinter_button").removeClass("ppp_bluebtn").addClass("ppp_graybtn").css("cursor","default");
         }     
      }
   });

   //发送按钮点击
   $(document).on('click', '#onlineinter_button', function(){
      if($(this).hasClass("ppp_graybtn")) {
         return false;
      }
      var target = $("#onlineinter_testdialog");
      var resume = resumecontent.attr('data-id');
      var sendsms = $('#onlineinter_testdialog #sendsms').val();
      $.ajax({
         type: "POST",
         url: OC.filePath('resumes', 'ajax', 'invitejobseeker.php'),
         data: {ids:JSON.stringify([resume]), sendsms:sendsms},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            if(result.status === 'success' && result.invite_date) {
               $('.invite_interview #invite_abtn').closest(".invite_interviewbtn").removeClass('invite_interviewbtn invite_interview').addClass('invite_havedone').html(result.invite_date + ' 邀请已发送');
               target.modal('hide');
               showStatusDialog('应聘邀请发送成功！');
            } else if(result.error) {
               showMessagePanel(result.error, target, true, {placement:'right',timeout:3000});
            } else {
               showMessagePanel('邀请失败', target, true, {placement:'left'});
            }
         }
      });
   });
   
   // folder manage
   $('#folder_dropdown').on('click', '.showlist', function() {
      $('#foldermanage_modal').modal('show');
      $.ajax({
         url: OC.filePath('resumes', 'ajax', 'getcustomfolderlist.php'),
         data: {searchurl: $('#folder_dropdown').data('searchurl')},
         beforeSend: function(xhr, settings) {
            showLoading($("#foldermanage_body"));
         },
         success: function(data) {
            $("#foldermanage_body").html(data);
         }
      });
   });
   
   // set resume jobposition
   $(document).on('click', '.setjob', function(){
      var jobseekerid = resumecontent.data('id');
      
      $(this).jobSelect({
         title: '选择职位',
         listurl: alljoblist_url,
         selected:function(){
            var fContainer = $(this);
            var jobObj = $('.itemlist a.selectjob.cur_a', fContainer);
            var confirmBtn = $('.selectjobconfirm', fContainer);
            if(jobObj.length > 0){
               $.ajax({
                  type: "POST",
                  url: OC.filePath('resumes', 'ajax', 'savejob.php'),
                  data: {jobid: jobObj.data('jobid'), jobseekerid: jobseekerid},
                  beforeSend: function(xhr, settings) {
                     if(!showLoading(confirmBtn, settings, null, {button:true}))
                        return false;
                     $('.server', fContainer).hide();
                  },
                  success: function(result){
                     if (!isLoggedIn(result, jQuery("#floatcontainer"))) {
                        window.location = redirect_url;
                        return;
                     }
                     
                     if(!$.isPlainObject(result)) {
                        result = $.parseJSON(result);
                     }
                     
                     if(result.status === 'success') {
                        fContainer.modal('hide');
                        window.location.reload();
                     } else {
                        showMessagePanel(result.data.message, confirmBtn, true, {placement:'right'});
                     }
                  }
               });
            } else {
               $('.server', fContainer).text('请选择职位').show();
            }
         },
         emptySelected:function(){
            $('.itemlist a.cur_a', $(this)).removeClass('cur_a');
         },
         cancelSelected:function(){
            $(".itemlist a.cur_a", $(this)).removeClass("cur_a");
            $('.resume_dialogposition').modal('hide');
         }
      });
   });

   //写评语弹出dialog js
   $("#writecommentsdialog span.ppp_whitebtn").click(function(){
      $(this).hide();
      $("#writecommentsdialog .cmts_txtwrap").show();
   });

   //统计剩余字符
   $('#writecommentsdialog textarea[maxcharlength]').each(function() {
      $(this).jobUtil("setInputLimit");
   });

   //隐藏弹出框
   $("#writecommentsdialog #cancelbtn").click(function(){
      $("#writecommentsdialog .cmts_txtwrap").hide();
      $("#writecommentsdialog span.ppp_whitebtn").show();
   });

   var show_comments = function (result) {
      var html = "";
      for(var i = 0; i < result.list.length; i++) {
         var type = parseInt(result.list[i].type);
         var delete_html = "";
         if(result.ismaster || result.list[i].isself) {
            delete_html = "<div style=\"text-align:right; padding:0 5px 5px 0; margin-top:-3px;\">" +
                "<a href=\"javascript:void(0);\" data-id=" + result.list[i].id + ">删除</a>" + "</div>";
         }
         html += "<div class=\"comments_eachline\" data-id=\"" + result.list[i].id + "\">" +
                     "<div class=\"comments_name clearfix\">" +
                        "<span>" + result.list[i].name + "</span><em>" + result.list[i].commented +"</em>" +
                     "</div>" + "<div class=\"comments_words\">" +
                        "<span>" + 
                           ( type & 1 ? "【电话】" : "" ) + ( type & 2 ? "【面谈】" : "" ) + ( type & 4 ? "【备注】" : "" ) +
                        "</span> " + 
                        result.list[i].commenttext + 
                     "</div>" + delete_html + 
                  "</div>";
      }
      $("#container").html(html);
      $(".comments_writeaction a").data("numtotal",result.total);
      $(".comments_writeaction a").data("numleft",result.left);
      if(result.total > 1) {
         $(".comments_writeaction a").html(result.left > 0 ? "(剩余" + result.left + "条)查看更多" : "收起");
      } else {
         $(".comments_writeaction a").html("");
      }
   }

   //提交评语
   $("#writecommentsdialog a.ppp_bluebtn").click(function(){
      var comment_area = $("#writecommentsdialog textarea");
      var comment_error = $("#writecommentsdialog div.error");
      var checkboxs = $("#writecommentsdialog input:checked[type='checkbox'][name='comment_type']");
      var comment_content = comment_area.val();
      var displayname = $("#writecommentsdialog").data("displayname");
      var jobseeker_id = $("#writecommentsdialog").data("jobseekerid");
      var limit = $("#container .comments_eachline:visible").length;
      limit = limit < 1 ? 1 : limit;
      if(comment_content.length <= 0) {
         comment_error.html("请输入评语").fadeIn(1500).fadeOut(1500); return;
      } else if(compact_strlen(comment_content) > 500) {
         comment_error.html("字符数超出限制").fadeIn(1500).fadeOut(1500); return;
      }
      var type = 0;
      checkboxs.each( function() { type += parseInt($(this).val()); });
      if(type == 0) { type = 4; }
      if(!jobseeker_id) {
         comment_error.html("添加评语失败").fadeIn(1500).fadeOut(1500); return;
      }
      $.ajax({
         type: "POST",
         url: resume_addcomments,
         data: {commenttext: comment_content, jobseeker_id: jobseeker_id, type: type, jobid: resumecontent.data('jobid'), limit: limit},
         beforeSend: function(xhr, settings) {
            if(!showLoading($("#container"), settings, null, {button:true}))
               return false;
         },
         success: function(result) {
            if(result.status == 'success') {
               $("#writecommentsdialog .cmts_txtwrap").hide();
               comment_area.val("");
               $('#writecommentsdialog textarea[maxcharlength]').each(function() {
                  $(this).jobUtil("setInputLimit");
               });
               checkboxs.each(function() { $(this).prop("checked",false); });
               $("#writecommentsdialog span.ppp_whitebtn").show();
               show_comments(result);
            } else {
               comment_error.html(result.error).fadeIn(1500).fadeOut(1500);
            }
         },
      });
   });

   //查看更多
   $(document).on('click', ".comments_writeaction a",  function(e, reload) {
      var jobseekerid = $("#writecommentsdialog").data("jobseekerid");
      var limit = $("#container .comments_eachline:visible").length;
      var numleft = $(".comments_writeaction a").data("numleft");
      $(this).addClass('collapsed');
      limit = limit + 5;
      //如果numleft为零,收起(隐藏其他记录，只显示初始状态的一条记录)
      if(numleft <= 0) {
         var numtotal = $(".comments_writeaction a").data("numtotal");
         $("#container .comments_eachline:gt(0)").hide();
         if(numtotal > 1) {
            numleft = numtotal - 1;
            $(".comments_writeaction a").data("numleft", numleft);
            $(".comments_writeaction a").html("(剩余" + numleft + "条)查看更多");
         }
         return;
      }
      $.ajax({
         type: "POST",
         url: resume_getcomments,
         data: {jobseeker_id: jobseekerid, limit: limit},
         beforeSend: function(xhr, settings) {
            if(!showLoading($("#container"), settings, null, {button:true}))
               return false;
         },
         success: function(result) {
            if(result.status == 'success') {
               show_comments(result);
            }
         }
      });
   });

   $(document).on('click', "#container .comments_eachline a", function(){
      var self_obj = $(this);
      var index = self_obj.parent().parent().index();
      var jobseeker_id = $("#writecommentsdialog").data("jobseekerid");
      var comment_id = self_obj.data("id");
      var limit = $("#container .comments_eachline:visible").length;
      showConfirmDialog('确认删除该评语？',function() {
         $.ajax({
            type: "POST",
            url: resume_delcomments,
            data: {comment_id: comment_id, jobseeker_id: jobseeker_id, limit: limit},
            beforeSend: function(xhr, settings) {
               if(!showLoading($("#container"), settings, null, {button:true}))
                  return false;
            },
            success: function(result) {
               if(result.status == 'success') {
                  show_comments(result);
               } else {
                  showMessageDialog(result.error);
               }
            }
         });
      });
   });

   //修改简历详情页匹配度dialog不随浏览器大小变位置变动问题
   $(window).resize(function(){
      if($("#match_details_pop").length > 0) {
         $("#match_details_pop").position({
           my: "left top+6",
           at: "left+20 bottom",
           of: $('.show_match_details.matched')
         });
      }
   });

});
